package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @Author: wf
 * @Desc:  全局异常处理类
 * @Date: 2022-08-22 16:14:57
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody       // 设置响应的是json数据
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 功能描述: 异常处理方法
     * @param ex
     * @return com.itheima.reggie.common.R<java.lang.String>
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        log.info(message);
        if (message.contains("Duplicate entry")){

            String[] split = message.split(" ");
            String msg = split[2] + "已经存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    /**
     * 功能描述: 异常处理方法
     * @param ex
     * @return com.itheima.reggie.common.R<java.lang.String>
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.info("customException抛出异常{}", ex.getMessage());

        return R.error(ex.getMessage());
    }

}
